package com.zero.lite.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zero.lite.admin.annotation.LoginAdmin;
import com.zero.lite.dao.entity.User;
import com.zero.lite.dao.service.IUserService;
import com.zero.lite.dao.utils.ResponseUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/user")
public class UserController {
    private final Log logger = LogFactory.getLog(UserController.class);

    @Autowired
    private IUserService userService;

    @GetMapping("/list")
    public Object list(@LoginAdmin Integer adminId,
                       String username, String mobile,
                       Page page){
        if(adminId == null){
            return ResponseUtil.fail401();
        }
        EntityWrapper<User> ew=new EntityWrapper<>();
        Page<User> data=userService.selectPage(page,ew);

        return ResponseUtil.PageOk(data);
    }

    @GetMapping("/username")
    public Object username(String username){
        if(StringUtils.isEmpty(username)){
            return ResponseUtil.fail402();
        }
        EntityWrapper<User> ew=new EntityWrapper<>();
        ew.eq("user_name",username);
        int total = userService.selectCount(ew);
        if(total == 0){
            return ResponseUtil.ok("不存在");
        }
        return ResponseUtil.ok("已存在");
    }


    @PostMapping("/create")
    public Object create(@LoginAdmin Integer adminId, @RequestBody User user){
        logger.debug(user);

        userService.insert(user);
        return ResponseUtil.ok(user);
    }

    @PostMapping("/update")
    public Object update(@LoginAdmin Integer adminId, @RequestBody User user){
        logger.debug(user);

        userService.updateById(user);
        return ResponseUtil.ok(user);
    }
}
